#include "widget.h"

#include "ui_widget.h"

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) {
  ui->setupUi(this);
  QString error;
  /*  进度条 */
  QString versionInfo = QString("表格分解 by smaller");
  setWindowTitle(versionInfo);
  /* 设置icon */
  setWindowIcon(QIcon(":/img/ico_64.ico"));

  on_delBox_clicked();
  on_addBox_clicked();

  connect(this, &Widget::exportXlsx, &procDoc, &xlsxProcTask::exportXlsx,
          Qt::UniqueConnection);
  connect(this, &Widget::setWorkParam, &procDoc, &xlsxProcTask::setWorkParam);
  connect(&procDoc, &xlsxProcTask::workFinished, this, &Widget::workFinished,
          Qt::UniqueConnection); // taskPool.setMaxThreadCount(8);

  connect(&procDoc, &xlsxProcTask::exportFinished, this,
          &Widget::exportXlsxFinished, Qt::UniqueConnection);
  procParam.sector.classType = noUse;

  initRd();
}

Widget::~Widget() {

  if (QProcess::NotRunning != procThreExec.state()) {
    procThreExec.close();
  }
  if (fileWatch) {
    delete fileWatch;
    fileWatch = NULL;
  }

  delete ui;
}

void Widget::exportXlsxFinished() {
  QMessageBox::information(this, "提示:", "导出表格成功!");
  ui->procBtn->setEnabled(true);
}

void Widget::defaultInitJson() {
  QJsonObject jsonObject, filterObj;
  QJsonArray jsonArrayList, jsonArrayOther;
  QJsonValue filterValue;
  jsonArrayList.append("二级部门");
  jsonArrayList.append("三级部门");
  jsonArrayList.append("四级部门");
  jsonObject.insert("删除表头", jsonArrayList);

  jsonArrayOther.append("开封");
  jsonArrayOther.append("开封二区");
  jsonArrayOther.append("新郑");
  filterObj.insert("自定义区域", jsonArrayOther);

  jsonObject.insert("筛选列", filterObj);

  QJsonDocument jsonDoc;
  jsonDoc.setObject(jsonObject);

  QFile tmpFile(configFile);
  /* 写入文件格式 */
  if (false == tmpFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
    QMessageBox::information(
        this,
        "警告:", QString("配置文件创建失败:%1").arg(tmpFile.errorString()));
    return;
  }
  tmpFile.write(jsonDoc.toJson());
  tmpFile.close();
}

void Widget::loadJson() {
  do {
    QByteArray fileData;
    QFile jsonFile(configFile);
    if (false == jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
      QMessageBox::information(
          this,
          "警告:", QString("配置文件无法打开:%1").arg(jsonFile.errorString()));
      break;
    }

    fileData = jsonFile.readAll();
    jsonFile.close();
    /* 加载数据到界面 */
    /* 读取五,六级部门 json文件 */
    QJsonParseError jsonError;
    QJsonDocument doc(QJsonDocument::fromJson(fileData, &jsonError));

    if (jsonError.error != QJsonParseError::NoError) {

      break;
    }
    /* 解析 */
    if (doc.isNull()) {
      QMessageBox::information(
          this, "配置加载错误:", QString("%1\n文件为空!").arg(configFile));
      break;
    }
    if (false == doc.isObject())
      break;

    QJsonObject objRoot = doc.object();
    if (objRoot.isEmpty())
      break;

    QJsonObject jsonObject, filterObj;
    QJsonArray delJsonArray, usrJsonArray, fiveJsonArray, sixJsonArray;
    QJsonValue delListValue, usrListValue, fiveListValue, sixListValue;
    QStringList delList, usrList, fiveList, sixList;
    if (objRoot.contains("删除表头")) {
      delListValue = objRoot.value("删除表头");
      delJsonArray = delListValue.toArray();
      for (int cnt = 0; cnt < delJsonArray.count(); cnt++) {
        delList << delJsonArray.at(cnt).toString();
      }
      ui->delEdit->setText(delList.join(","));
    }
    if (objRoot.contains("筛选列")) {
      QJsonObject objFilter = objRoot.value("筛选列").toObject();
      if (objFilter.isEmpty())
        break;

      // index = objFilter.toVariantList().indexOf(QString("自定义区域"));
      if (objFilter.contains("自定义区域")) {
        usrListValue = objFilter.value("自定义区域");
        usrJsonArray = usrListValue.toArray();
        for (int cnt = 0; cnt < usrJsonArray.count(); cnt++) {
          usrList << usrJsonArray.at(cnt).toString();
        }

        ui->filterUserEdit->setPlainText(usrList.join(","));
      }
    }
  } while (0);
}

void Widget::initRd() {
  configFile =
      QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) +
      QString("/exlsConfig.json");
  QFileInfo fInfo(configFile);
  if (false == fInfo.isFile()) {
    if (fInfo.exists()) {
      /* 有同名目录 */
      configFile =
          QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) +
          QString("/xlsConfig.json");
    }
    defaultInitJson();
  }
  if (fInfo.size() == 0) {
    defaultInitJson();
  }

  loadJson();

  EditTools = QCoreApplication::applicationDirPath() +
              QString("/npp.7.8.9.bin/notepad++.exe");

  /* 监视配置文件 */

  fileWatch = new QFileSystemWatcher(this);
  connect(fileWatch, &QFileSystemWatcher::fileChanged, this, &Widget::loadJson);
  fileWatch->addPath(configFile);
}

void Widget::on_selectFileBtn_clicked() { /* 选择文件 */
  QString file = QFileDialog::getOpenFileName(
      this, tr("打开表格(excel)文件"),
      QStandardPaths::writableLocation(QStandardPaths::DesktopLocation),
      tr("表格文件 (*.xls *.xlsx)"));
  if (file.isEmpty()) {
    QMessageBox::information(this, "打开错误", "未选择表格文件\n");
    return;
  }
  ui->selectFileEdit->setText(file);
  procParam.xlsxName = file;
  emit setWorkParam(procParam);
}

void Widget::on_selectDirBtn_clicked() { /* 选择输出目录 */
  QString dir = QFileDialog::getExistingDirectory(
      this, tr("选择路径"),
      QStandardPaths::writableLocation(QStandardPaths::DesktopLocation),
      QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
  if (dir.isEmpty()) {
    QMessageBox::information(this, "打开错误", "未选择输出路径\n");
    return;
  }
  ui->selectDirEdit->setText(dir);
  procParam.savePath = ui->selectDirEdit->text();
  emit setWorkParam(procParam);
}

void Widget::on_delBox_clicked() {
  if (ui->delBox->isChecked()) {
    ui->delEdit->setEnabled(true);
    procParam.delColumn.isDel = true;
    procParam.delColumn.delCoumnList = ui->delEdit->text().split(",");
  } else {
    ui->delEdit->setEnabled(false);
    ui->delEdit->clear();
    procParam.delColumn.isDel = false;
  }
  emit setWorkParam(procParam);
}

void Widget::on_addBox_clicked() {
  if (ui->addBox->isChecked()) {
    ui->addEdit->setEnabled(true);
    ui->sumEdit->setEnabled(true);
  }
}

void Widget::on_filterUserBtn_clicked() {
  if (ui->filterUserBtn->isChecked()) {
    ui->filterUserEdit->setEnabled(true);
    on_filterUserEdit_textChanged();
  }
}

void Widget::on_filterUserFiveBtn_clicked() {
  if (ui->filterUserFiveBtn->isChecked()) {
    ui->filterUserEdit->setEnabled(true);
    on_filterUserEdit_textChanged();
  }
}

void Widget::erroInfo(QString errorString) { qDebug() << errorString; }
void Widget::workFinished() {
  QMessageBox::information(this, "提示:", "处理完成!");
  ui->procBtn->setEnabled(true);
}
void Widget::procProcss(double, qint64, qint64) {}

void Widget::on_procBtn_clicked() { /* 处理表格 */
  on_filterUserBtn_clicked();
  on_filterUserFiveBtn_clicked();
  on_delBox_clicked();
  emit exportXlsx();

  ui->procBtn->setEnabled(false);
}

void Widget::on_saveCfgBtn_clicked() {

  QJsonObject jsonObject, filterObj;
  QJsonArray jsonArrayList, jsonArrayFive, jsonArraySix, jsonArrayOther;
  QJsonValue filterValue;
  QStringList delList, usrList, fiveList, sixList;
  delList = ui->delEdit->text().simplified().remove(QRegExp("\\s")).split(",");
  for (int cnt = delList.count() - 1; cnt >= 0; cnt--) {
    if (delList.at(cnt).isEmpty()) {
      delList.removeAt(cnt);
    } else {
      jsonArrayList.insert(0, delList.at(cnt));
    }
  }
  jsonObject.insert("删除表头", jsonArrayList);

  filterObj.insert("六级部门", jsonArraySix);

  usrList = ui->filterUserEdit->toPlainText()
                .simplified()
                .remove(QRegExp("\\s"))
                .split(",");
  for (int cnt = usrList.count() - 1; cnt >= 0; cnt--) {
    if (usrList.at(cnt).isEmpty()) {
      usrList.removeAt(cnt);
    } else {
      jsonArrayOther.insert(0, usrList.at(cnt));
    }
  }
  filterObj.insert("自定义区域", jsonArrayOther);

  jsonObject.insert("筛选列", filterObj);

  QJsonDocument jsonDoc;
  jsonDoc.setObject(jsonObject);

  QFile tmpFile(configFile);
  /* 写入文件格式 */
  if (false == tmpFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
    QMessageBox::information(
        this,
        "警告:", QString("配置文件创建失败:%1").arg(tmpFile.errorString()));
    return;
  }
  tmpFile.write(jsonDoc.toJson());
  tmpFile.close();
}

void Widget::on_editCfgBtn_clicked() { /* npp.7.8.9.bin/notepad++.exe */
  QStringList strList;
  if (QProcess::NotRunning != procThreExec.state()) {
    procThreExec.close();
  }
  strList << configFile;
  procThreExec.start(EditTools, strList, QIODevice::ReadWrite);
}

void Widget::on_filterUserEdit_textChanged() {
  if (ui->filterUserBtn->isChecked()) {
    procParam.sector.classType = sixGet;
  } else if (ui->filterUserFiveBtn->isChecked()) {
    procParam.sector.classType = fiveGet;
  } else {
    procParam.sector.classType = noUse;
  }
  procParam.sector.classList.clear();
  procParam.sector.classList = ui->filterUserEdit->toPlainText().split(",");
  /*  */
  for (int i = procParam.sector.classList.count() - 1; i > 0; i--) {
    if (procParam.sector.classList.at(i).isEmpty()) {
      procParam.sector.classList.removeAt(i);
    }
  }
  if (procParam.sector.classList.isEmpty())
    return;
  emit setWorkParam(procParam);
}

void Widget::on_sixSplitBtn_clicked() {
  if (ui->sixSplitBtn->isChecked()) {
    ui->filterUserEdit->setEnabled(false);

    procParam.sector.classType = sixSplit;
  }

  emit setWorkParam(procParam);
}
